package com.td.filemanager.business.filedetail;

import com.td.filemanager.MyApplication;
import com.td.filemanager.ResourceTable;
import com.td.filemanager.business.filethumbnail.FileThumbnailViewModel;
import com.td.library.config.FileType;

import com.td.filemanager.slice.BaseAbilitySlice;
import com.td.filemanager.ui.GeneralButtonElement;
import com.td.filemanager.ui.GeneralDialog;
import com.td.filemanager.ui.widget.ActionBar;
import com.td.library.utils.FileUtils;
import com.td.lib.viewmodel.DefaultDataObserver;
import com.td.lib.viewmodel.ViewModelAbility;
import com.td.lib.viewmodel.ViewModelProvider;
import com.td.library.data.FileData;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 文件详情页
 */
public class FileDetailAbilitySlice extends BaseAbilitySlice {
    private static final String TAG = FileDetailAbilitySlice.class.getSimpleName();

    private Image mImage;
    private Component mDetail;
    private Component mDownload;
    private ActionBar mActionBar;

    private FileDetailViewModel mViewModel;


    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_slice_file_detail);
        initComponent();
        initViewModel();
        initListener();
        initObserver();
    }


    private void initComponent() {
        mImage = (Image) findComponentById(ResourceTable.Id_image);
        mDetail = findComponentById(ResourceTable.Id_detail);
        mDownload = findComponentById(ResourceTable.Id_download);
        mActionBar = (ActionBar) findComponentById(ResourceTable.Id_actionBar);
        mActionBar.setLeftClickListener(component -> {
            terminate();
        });
    }

    private void initListener() {
        mDetail.setClickedListener(component -> {
            FileData fileData = mViewModel.getFileData().getData();
            File file = new File(fileData.getAbsolutePath());
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            String fileInfo = "文件名：" + fileData.getName() + System.lineSeparator() +
                    "是否本机：" + fileData.getDeviceData().isLocal() + System.lineSeparator() +
                    "设备名：" + fileData.getDeviceData().getDeviceName() + System.lineSeparator() +
                    "设备id：" + fileData.getDeviceData().getDeviceId() + System.lineSeparator() +
                    "文件路径：" + fileData.getAbsolutePath() + System.lineSeparator() +
                    "文件大小：" + file.length() + System.lineSeparator() +
                    "能否读：" + file.canRead() + System.lineSeparator() +
                    "能否写：" + file.canWrite() + System.lineSeparator();
            builder.setTitle("文件详情信息查看")
                    .setOutsideTouchClosable(true)
                    .setContent(fileInfo)
                    .addButton("关闭", GeneralButtonElement.TYPE_ACCENT, GeneralDialog::remove)
                    .create()
                    .show();
        });

        mDownload.setClickedListener(component -> {
            MyApplication.getInstance().getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
                FileData fileData = mViewModel.getFileData().getData();
                File file = new File(fileData.getAbsolutePath());
                try (FileInputStream fileInputStream = new FileInputStream(file)) {
                    Date date = new Date(System.currentTimeMillis());
                    String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    boolean success = FileUtils.saveToDownloads(MyApplication.getInstance(), fileInputStream, file.getPath(),
                            sdf.format(date) + "————" + file.getName());
                    MyApplication.getInstance().getUITaskDispatcher().asyncDispatch(() -> {
                        new ToastDialog(getContext())
                                .setText("保存至下载路径：" + success)
                                .show();
                    });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });
    }


    private void initViewModel() {
        if (getAbility() instanceof ViewModelAbility) {
            ViewModelAbility viewModelAbility = (ViewModelAbility) getAbility();
            mViewModel = new ViewModelProvider(viewModelAbility.getViewModelStore())
                    .get(FileDetailViewModel.class);
            FileThumbnailViewModel fileThumbnailViewModel =
                    new ViewModelProvider(viewModelAbility.getViewModelStore()).get(FileThumbnailViewModel.class);

            mViewModel.setFileData(fileThumbnailViewModel.getFileData().getData()
                    .get(fileThumbnailViewModel.getSelectFilePos()));
        }
    }

    private void initObserver() {
        mViewModel.getFileData().addObserver(new DefaultDataObserver<FileData>(getLifecycle()) {
            @Override
            public void onChanged(FileData fileData) {
                if (FileType.IMAGE.equals(fileData.getFileType())) {
                    ImageSource.SourceOptions opts = new ImageSource.SourceOptions();
                    ImageSource imageSource = ImageSource.create(fileData.getAbsolutePath(), opts);
                    ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                    PixelMap map = imageSource.createPixelmap(decodingOptions);
                    if (map != null) {
                        mImage.setPixelMap(map);
                    }
                } else {
                    mImage.setPixelMap(ResourceTable.Media_not_support_preview);
                }
            }
        }, false);
    }

}
